package org.gl.android.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.gl.GlobalVariable;
import org.gl.android.utils.BitmapUtil;
import org.gl.utils.lg;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chanceit.ssss.activity.R;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ImageUploadActivity extends Activity {
	public final static int RequestCode_ImageUpload = 520;
	public final static String ImageUpload = "uploadUrl";
	public final static String LocalImageUrl = "localImageUrl";
	public final static String ImageUploadResuleExtraKey = "uploadResult";

	private TextView mText1;
	private TextView mText2;
	private View mButton;
	private View Btn_camera;
	private View Btn_Gally;
	private final int RequestCode_Carmer = 1;
	private final int RequestCode_Gallay = 2;
	private String TAG = "ImageUploadActivity";
	private String picPath;
	private Bitmap bitmap;
	boolean isUpload = false;

	String tempPath = Environment.getExternalStorageDirectory() + "/temp.jpg";
	/**
	 * for test
	 */
	String uploadUrl = GlobalVariable.URL_image_upload;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) { 
			case 0:

				break;
			case 1:// START
				findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
				break;
			case 2:// FAIL
				findViewById(R.id.progressBar1).setVisibility(View.GONE);
				alert("update fail ,try again");
				mButton.setVisibility(View.VISIBLE);
				findViewById(R.id.button).setEnabled(true);
				findViewById(R.id.button1).setEnabled(true);
				findViewById(R.id.progressBar1).setVisibility(View.GONE);
				mText2.setVisibility(View.GONE);
				break;
			case 3:// success
					// alert("update success,result:" + msg.obj);
				setResult(
						RESULT_OK,
						getIntent().putExtra(ImageUploadResuleExtraKey,
								msg.obj.toString()).putExtra(LocalImageUrl,
								picPath));
				isUpload = true;
				findViewById(R.id.progressBar1).setVisibility(View.GONE);
				mText2.setVisibility(View.GONE);
				onBackPressed();
				break;
			case 4:// loading
				System.out.println(msg.arg1 + "/" + msg.arg2);
				if (msg.arg2 != 0) {
					mText2.setText(String.format("%.2f",
							((float) (msg.arg1 / msg.arg2)) * 100) + "%");
				}
				break;
			case 5:// loading
					mText2.setText("压缩图片");
				break;

			default:
				break;
			}
		}
	};
	private ImageView imageView;

	@Override
	protected void onStart() {
		super.onStart();
		findViewById(R.id.rl_root).setBackgroundColor(0xffe9eaee);
	};

	@Override
	protected void onRestart() {
		super.onRestart();
		findViewById(R.id.rl_root).setBackgroundColor(0xffe9eaee);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			Log.v("TestFile", "SD card is not avaiable/writeable right now.");
			alert("SD card is not avaiable/writeable right now.");
			finish();
			return;
		}
		setContentView(R.layout.upload_image);
		
		picPath = getIntent().getStringExtra(LocalImageUrl);
		imageView = ((ImageView) findViewById(R.id.textView5));
		if (!TextUtils.isEmpty(picPath)) {
			ImageLoader.getInstance().displayImage(
					"file://"+picPath, imageView);
		}
		
		mButton = findViewById(R.id.myButton);
		mButton.setVisibility(View.GONE);
		mButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				uploadUrl = (getIntent().getStringExtra(ImageUpload) == null ? uploadUrl
						: getIntent().getStringExtra(ImageUpload));
				// mText1 = (TextView) findViewById(R.id.myText2);
				// mText1.setText("//" + picPath);
				mText2 = (TextView) findViewById(R.id.myText3);
				mText2.setVisibility(View.VISIBLE);
				// mText2.setText("//" + uploadUrl);
				mButton.setVisibility(View.GONE);
				findViewById(R.id.button).setEnabled(false);
				findViewById(R.id.button1).setEnabled(false);
				new Thread() {
					public void run() {
						handler.sendEmptyMessage(1);
						try {
							handler.sendEmptyMessage(5);
							picPath = BitmapUtil.compressBitmapToFile(picPath);
							
						} catch (IOException e) {
							e.printStackTrace();
						}
						final String result = UploadUtil.uploadFile(new File(
								picPath), uploadUrl,
								new UploadUtil.UploadListener() {
									@Override
									public void loadsucess() {
									}

									@Override
									public void loading(long progress,
											long total) {
										handler.removeMessages(4);
										lg.i(TAG, progress + "/" + total);
										handler.sendMessage(handler
												.obtainMessage(4,
														(int) progress,
														(int) total));
									}

									@Override
									public void loadfail() {
									}
								});
						if (TextUtils.isEmpty(result)) {
							handler.sendEmptyMessage(2);
						} else {
							handler.sendMessage(handler
									.obtainMessage(3, result));
						}
					};
				}.start();
				// AjaxParams params = new AjaxParams();
				// try {
				// params.put("profile_picture2", new File(picPath));
				// FinalHttp fh = new FinalHttp();
				// fh.post(uploadUrl, params, new AjaxCallBack<String>() {
				// @Override
				// public void onStart() {
				// super.onStart();
				// mText2.setVisibility(View.VISIBLE);
				// handler.sendEmptyMessage(1);
				// }
				//
				// @Override
				// public void onLoading(long count, long current) {
				// System.out.println(current + "/" + count);
				// mText2.setText(current + "/" + count);
				// }
				// @Override
				// public void onFailure(Throwable t, int errorNo,
				// String strMsg) {
				// super.onFailure(t, errorNo, strMsg);
				// handler.sendEmptyMessage(2);
				// }
				// @Override
				// public void onSuccess(String result) {
				// mText2.setVisibility(View.GONE);
				// if (TextUtils.isEmpty(result)) {
				// handler.sendEmptyMessage(2);
				// } else {
				// handler.sendMessage(handler.obtainMessage(3,
				// result));
				// }
				// }
				// });
				// } catch (FileNotFoundException e) {
				// e.printStackTrace();
				// } // 上传数据流
			}
		});
		Btn_camera = findViewById(R.id.button);
		Btn_camera.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// �������
				File out;
				try {
					out = getTempFile();
					Uri uri = Uri.fromFile(out);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
					startActivityForResult(intent, RequestCode_Carmer);
				} catch (IOException e) {
					e.printStackTrace();
					alert("创建临时图片失败");
				}
				
			}

		});
		Btn_Gally = findViewById(R.id.button1);
		Btn_Gally.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, RequestCode_Gallay);
			}

		});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {
			destoryBitmap();
			switch (requestCode) {
			case RequestCode_Carmer:
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
					Log.v("TestFile",
							"SD card is not avaiable/writeable right now.");
					alert("SD card is not avaiable/writeable right now.");
					return;
				}

				if (new File(tempPath).exists()) {
					picPath = tempPath;
					ImageLoader.getInstance().displayImage(
							"file://"+picPath,
							((ImageView) findViewById(R.id.textView5)));
					// bitmap = BitmapFactory.decodeStream(cr
					// .openInputStream(uri));
					// ((ImageView) findViewById(R.id.textView5))
					// .setImageBitmap(bitmap);
				} else {
					alert();
				}
				mButton.setVisibility(View.VISIBLE);
				break;
			case RequestCode_Gallay:
				Uri uri = data.getData();
				Log.i(TAG, "uri = " + uri);
				try {
					String[] pojo = { MediaStore.Images.Media.DATA };
					Cursor cursor = managedQuery(uri, pojo, null, null, null);
					if (cursor != null) {
						ContentResolver cr = this.getContentResolver();
						int colunm_index = cursor
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						cursor.moveToFirst();
						String path = cursor.getString(colunm_index);
						if (path.endsWith("jpg") || path.endsWith("png")) {
							picPath = path;
							ImageLoader.getInstance().displayImage(
									"file://"+picPath,
									((ImageView) findViewById(R.id.textView5)));
							// bitmap = BitmapFactory.decodeStream(cr
							// .openInputStream(uri));
							// ((ImageView) findViewById(R.id.textView5))
							// .setImageBitmap(bitmap);
						} else {
							alert();
						}
					} else {
						alert();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				mButton.setVisibility(View.VISIBLE);
				super.onActivityResult(requestCode, resultCode, data);
				break;

			default:
				break;
			}

		} else {
			alert();
		}
	}

	private void alert() {
		Toast.makeText(getBaseContext(), "pick image fail", Toast.LENGTH_SHORT)
				.show();

	}

	private void alert(String s) {
		Toast.makeText(getBaseContext(), "" + s, Toast.LENGTH_SHORT).show();

	}

	@Override
	protected void onDestroy() {
		destoryBitmap();
		super.onDestroy();
	}

	private void destoryBitmap() {
		if (bitmap != null && !bitmap.isRecycled()) {
			bitmap.recycle();
			bitmap = null;
		}
	}

	@Override
	public void onBackPressed() {

		if (isUpload) {
			mButton.setVisibility(View.GONE);
			Btn_camera.setVisibility(View.GONE);
			Btn_Gally.setVisibility(View.GONE);
			findViewById(R.id.textView4).setVisibility(View.GONE);
			findViewById(R.id.textView1).setVisibility(View.GONE);
			findViewById(R.id.linediver).setVisibility(View.GONE);
			findViewById(R.id.rl_bg).setBackgroundColor(0x00000000);
			findViewById(R.id.rl_root).setBackgroundColor(0x00000000);
			super.onBackPressed();
			overridePendingTransition(R.anim.fade_in_two_second,
					R.anim.scale_left_down_out);
		} else {
			super.onBackPressed();
		}

	}

	/**
	 * ��ȡ·���е�ͼƬ��Ȼ����ת��Ϊ���ź��bitmap
	 * 
	 * @param path
	 */
	public String saveBefore(String path) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(path, options);
		options.inJustDecodeBounds = false;
		int be = (int) (options.outHeight / (float) 200);
		if (be <= 0)
			be = 1;
		options.inSampleSize = 4;
		bitmap = BitmapFactory.decodeFile(path, options);
		// savePNG_After(bitmap,path);
		return saveJPGE_After(bitmap, path);
	}

	/**
	 * 
	 * @param bitmap
	 * @param path
	 */
	public String saveJPGE_After(Bitmap bitmap, String path) {
		File file = new File(path);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return path;
	}

	private File getTempFile() throws IOException {
		File out = new File(tempPath);
		int i =0;
		while(out.exists()){
			i++;
			tempPath = Environment.getExternalStorageDirectory()+"/"+i+"temp.jpg";
			out = new File(tempPath);
		}
		out.createNewFile();
		return out;
	}
}
